package com.study.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.study.utils.JwtHelper;
import com.study.utils.Result;
import com.study.utils.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * description:登录保护拦截器，检查请求头中是否携带token，
 * 如果携带则验证token是否过期，如果过期则返回504错误信息，如果未过期则放行
 */
@Component // 将拦截器交给spring容器管理
public class LoginProtectedInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("token");
        // 判断token是否为空（有效），如果为空则返回false，表示拦截请求
        boolean expiration = jwtHelper.isExpiration(token);
        //有效则放行
        if (!expiration){
            return true;
        }
        // 无效则返回504状态的json
        Result result = Result.build(null, ResultCodeEnum.NOTLOGIN);

        //将数据转换为json ，并返回给前端
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(result);
        response.getWriter().printf(json); // 将json数据返回给前端

        return false;
    }
}
